//统计用户浏览到条目底部
function wikiStatViewFinish(stateViewFinishType)
{
	var stateViewFinishTag = 0;
    	$(window).scroll(function(){
    		viewFinish();
        });


        function viewFinish()
        {
		if(stateViewFinishTag == 1) return false;
        	var w_height = $(window).height();//是文档窗口高度
        	var d_top = $(".main_content").offset().top//是标签距离顶部高度
        	var scroll_top = $(document).scrollTop();//是滚动条高度
        	var d_height = $(".main_content").height();//是标签高度
        	var h = d_height + d_top - scroll_top - w_height;
        	if(h <= 0)
        	{
        		stateViewFinishTag = 1;
			if(typeof statWikiViewFinish === 'function' )
				statWikiViewFinish(stateViewFinishType);
		}
        }
}

//选中文字
document.onmouseup = document.ondbclick= function(){
 var txt;
 if(document.selection){
  txt = document.selection.createRange().text
 }else{
  txt = window.getSelection()+'';
 }
 if(txt){
	 if(typeof statWikiSelection === 'function')
	 {
		 statWikiSelection();
	 }
 }
}

//复制监听
document.oncopy = function(){
	var txt;
	if(document.selection){
		txt = document.selection.createRange().text
	}else{
		txt = window.getSelection()+'';
	}
	if(txt){
		if(typeof statWikiCopy === 'function')
		{
			statWikiCopy();
		}
	}
}




//百科模板v2 js
//initV2();
function initV2()
{
	$(function(){
		$(document).on("click",".reply_t_show",function(){
			var reply = $(this).parents(".comment-cont").find(".reply-content-wrap");
			if(reply.hasClass("hid"))
				$(this).parents(".comment-cont").find(".reply-content-wrap ").removeClass('hid');
			else
				$(this).parents(".comment-cont").find(".reply-content-wrap ").addClass('hid');
		})
	});
}

function wikiGetCookie(name)
{
	var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
	if(arr=document.cookie.match(reg))
		return unescape(arr[2]);
	else
		return null;
}

function wikiSetCookie(c_name,value,minute,domain)
{
	var exdate=new Date();
	//exdate.setDate(exdate.getDate()+expiredays);
	exdate.setTime(exdate.getTime()+60*1000*minute);
	document.cookie=c_name+ "=" +escape(value)+";path=/;domain="+domain+
		((minute==null) ? "" : ";expires="+exdate.toGMTString());
}

//防抖
function debounce(func, wait) {
	if (typeof func !== 'function') {
		throw new TypeError('need a function arguments')
	}

	var timeid = null;
	var result;

	return function() {
		var context = this;
		var args = arguments;

		if (timeid) {
			clearTimeout(timeid);
		}
		timeid = setTimeout(function() {
			result = func.apply(context, args);
		}, wait);

		return result;
	}
}


function autoCompleteInput(){
	var loading = $(this).attr('data-loading') || 0;
	if(loading==1){
		console.log('加载中...');
		return;
	}
	var keyword = $(this).val();
	var _this = this;
	if(keyword){
		$(this).attr('data-loading',1);
		$.post('https://www.mbalib.com/s/comple',{keyword:keyword,type:'wiki'},function(result){
			$(_this).attr('data-loading',0);
			var list = result.data;
			completeSearchList(list,keyword);
		},'json');
	}else{
		// $("#ss-comple-list").empty();
		$(".ss-comple").remove();
	}
}

function completeSearchList(list, keyword){
	if(list && list.length){
		var dom = $("<div class='ss-comple'><ul id='ss-comple-list' class='ss-comple-ul'></ul></div>")
		if(!$("#ss-comple-list").length){
			$("#searchInput").after(dom)
		}
		$("#ss-comple-list").empty();

		var html ='';
		for(var i=0; i<list.length;i++){
			var word = list[i].replace(keyword,'<span class="m-font-grey">'+keyword+'</span>');
			html+='<li data-word="'+list[i]+'">'+word+'</li>';
		}
		$("#ss-comple-list").html(html);
	}
}

$(function(){

	wfViewLog("wiki",wgTitle);

	//搜索词补全
	$('#searchInput').bind('input propertychange', debounce(autoCompleteInput, 350));
	$('#searchInput').bind('focus',function(e){
		$('.searchform-search,.ss-masker').addClass('focus');
		var keyword = $(this).val();
		if(keyword){
			//如果列表是空的，去查询获取
			autoCompleteInput.bind(this)();
		}
	})
	document.addEventListener('click', function(e){
		var el = document.getElementsByClassName("searchform-search")[0];
		if (el.contains(e.target)) {
			return false;
		}
		$('.searchform-search,.ss-masker').removeClass('focus');
		return false;
	});
	$('.searchform-search').on('mousedown','#ss-comple-list li',function(e){
		e.preventDefault();
	})
	$('.searchform-search').on('mouseenter', '#ss-comple-list li', function() {
		$(this).addClass('ss-select').siblings().removeClass('ss-select');
	});

	$('.searchform-search').on('click','#ss-comple-list li',function(e){
		var word = $(this).attr('data-word');
		var url = '/wiki/'+word;
		location.href = url;
	})

	$(document).keydown(function (event) {
		var dom = $("#ss-comple-list .ss-select");
		var upDownClickNum  = 0;
		if(dom){
			upDownClickNum = $("#ss-comple-list li").index(dom);
		}

		 var length = $("#ss-comple-list li").length;

        if ($("#ss-comple-list").css("display") == "block") {
            //38:上  40:下
            if (event.keyCode == 38) {
               upDownClickNum--;
			   upDownClickNum = upDownClickNum<0?0:upDownClickNum;
               event.preventDefault();//阻止光标移动

            } else if (event.keyCode == 40) {
				upDownClickNum++;
				upDownClickNum = upDownClickNum>length? length:upDownClickNum;
                event.preventDefault();
            }

			if(event.keyCode == 38 || event.keyCode == 40){
				$("#ss-comple-list li").eq(upDownClickNum).addClass('ss-select').siblings().removeClass('ss-select');
				var word = $("#ss-comple-list .ss-select").attr('data-word');
				$('#searchInput').val(word);
			}
        }
	});
})
